package ru.amse.tsyganov.jumleditor.view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Cursor;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;

import ru.amse.tsyganov.jumleditor.commands.Command;
import ru.amse.tsyganov.jumleditor.commands.CommandFactory;
import ru.amse.tsyganov.jumleditor.editor.EditorUtil;
import ru.amse.tsyganov.jumleditor.model.State;
import ru.amse.tsyganov.jumleditor.model.StateVertex;
import ru.amse.tsyganov.jumleditor.model.Transition;

public abstract class TransitionActivePoint extends ActivePoint {
	private final boolean sourceMoving;
	
	public TransitionActivePoint(boolean sourceMoving) {
		this.sourceMoving = sourceMoving;
	}
	
	public abstract Transition getModel();
	
	@Override
	public final Cursor createCursor() {
		return new Cursor(null, SWT.CURSOR_SIZEALL);
	}

	@Override
	public final void paintTempResult(GC gc) {
		gc.setForeground(Colors.grayColor);
		gc.setBackground(Colors.grayColor);
		
		State state = (sourceMoving) ? 
				getModel().getTarget().getContainer() :
					getModel().getSource().getContainer();
				
		TransitionDraughtsman.drawArrowedLine(gc, 
				TransitionDraughtsman.getLine(
						new Point(
								getTemporaryActivePointX(), 
								getTemporaryActivePointY()), 
						ModelViewMap.map.getStatesMap().get(state).getRectangle()), 
					sourceMoving);
	}

	@Override
	public final Command perform() {
		StateView<? extends State> newStateView = 
			EditorUtil.getStateView( 
					getTemporaryActivePointX(), 
					getTemporaryActivePointY());
		
		if (newStateView == null) {
			return null;
		}
		
		StateVertex newSourceVertex = (sourceMoving) ? 
				newStateView.getModel().getStateVertex() :
					getModel().getSource();
				
		StateVertex newTargetVertex = (!sourceMoving) ? 
				newStateView.getModel().getStateVertex() :
					getModel().getTarget();
		
		return CommandFactory.createMoveTransitionCommand(
				ModelViewMap.map.getTransitionsMap().get(getModel()), 
				newSourceVertex, newTargetVertex);
	}

}
